<?php

namespace app\common\model;

use think\Db;
use think\Validate;

class ShopGoodsModel extends BaseModel
{
    protected $name = 'shop_goods'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    //读取缩略图
    protected function getGoodsThumbAttr($value, $data)
    {
        if (empty($data['album'])) {
            return '';
        } else {
            $album = explode('|', $data['album']);
            return $album[0];
        }
    }

    //格式化内容
    protected function setGoodsContentExtendAttr($value, $data)
    {
        if ($data['goods_content_extend']) {
            foreach ($data['goods_content_extend']['key'] as $k => $v) {
                $list[$k] = $v . ":" . $data['goods_content_extend']['value'][$k];
            }
            $list = implode(",", $list);
            return $list;
        }
        return '';
    }

    /**
     * 读取商品信息
     * @param $goodsId
     * @return array
     */
    public function getInfo($goodsId)
    {
        $goodsInfo      = $this->where('goods_id', $goodsId)->find();
        $goodsInfo      = $goodsInfo->append(['goods_thumb'])->toArray();
        $goodsDataModel = new ShopGoodsDataModel();
        $goodsData      = $goodsDataModel->where('goods_id', $goodsId)->find()->toArray();
        $info           = array_merge($goodsInfo, $goodsData);
        return $info;
    }

    /**
     * 获取商品sku信息
     * @param $skuId
     */
    public function getSkuInfo($skuId)
    {
        $goodsSkuModel = new ShopGoodsSkuModel();
        $skuInfo       = $goodsSkuModel->where('sku_id', $skuId)->find()->toArray();
        $goodsInfo     = $this->where('goods_id',$skuInfo['goods_id'])->find()->toArray();
        $skuInfo                = array_merge($goodsInfo, $skuInfo);
        $skuInfo                = format_goods_content($skuInfo);
        return $skuInfo;
    }

    /**
     * 取得商品最新的属性及促销[立即购买]
     * @param int $goods_id
     * @param int $quantity
     * @return array
     */
    public function getSkuOnlineInfo($skuId,$number) {
        $skuInfo = $this->_getSkuOnlineInfo($skuId,$number);

        //限时折扣
        $this->getXianshiInfo($goods_info,$goods_info['goods_num']);

        //赠品
        $this->_getGoodsGiftList($goods_info);

        return $goods_info;
    }

    /**
     * 直接购买时返回最新的在售商品信息（需要在售）
     *
     * @param int $skuId 所购商品ID
     * @param int $number 购买数量
     * @return array
     */
    private function _getSkuOnlineInfo($skuId,$number) {
        //取目前在售商品
        $skuInfo = $this->getSkuInfo($skuId);
        if(empty($skuInfo)){
            return [];
        }
        $newSkuInfo = [];
        $newSkuInfo['cart_id'] = $skuId;
        $newSkuInfo['site_id'] = $skuInfo['site_id'];
        $newSkuInfo['site_name'] = $skuInfo['site_name'];
        $newSkuInfo['goods_id'] = $skuInfo['goods_id'];
        $newSkuInfo['sku_id'] = $skuInfo['sku_id'];
        $newSkuInfo['goods_name'] = $skuInfo['goods_name'];
        $newSkuInfo['sku_name'] = $skuInfo['sku_name'];
        $newSkuInfo['minimum'] = $skuInfo['minimum'];
        $newSkuInfo['step'] = $skuInfo['step'];
        $newSkuInfo['goods_unit'] = $skuInfo['goods_unit'];
        $newSkuInfo['goods_thumb'] = $skuInfo['goods_thumb'];
        $newSkuInfo['goods_price'] = $skuInfo['goods_price'];
        $newSkuInfo['cart_price'] = $skuInfo['simple_price'];
        $newSkuInfo['cart_num'] = $number;
        $newSkuInfo['bl_id'] = 0;
        $newSkuInfo['state'] = true;
        $newSkuInfo['stock_state'] = intval($skuInfo['goods_stock']) < intval($number) ? false : true;
        $newSkuInfo['simple_price'] = $skuInfo['simple_price'];
        $newSkuInfo['goods_freight'] = $skuInfo['goods_freight'];
        $newSkuInfo['goods_stock'] = $skuInfo['goods_stock'];
        $newSkuInfo['have_gift'] = $skuInfo['have_gift'];
        $newSkuInfo['promotion_type'] = $skuInfo['promotion_type'];
        return $newSkuInfo;
    }

    /**
     * 直接购买时，判断商品是不是正在抢购中，如果是，按抢购价格计算，购买数量若超过抢购规定的上限，则按抢购上限计算
     * @param array $goods_info
     */
    public function getGroupbuyInfo(& $skuInfo = []) {
        if (empty($skuInfo['groupbuy_info'])) return ;
        $groupbuy_info = $goods_info['groupbuy_info'];

        $goods_info['goods_price'] = $groupbuy_info['groupbuy_price'];
        if ($groupbuy_info['upper_limit'] && $goods_info['goods_num'] > $groupbuy_info['upper_limit']) {
            $goods_info['goods_num'] = $groupbuy_info['upper_limit'];
        }
        $goods_info['upper_limit'] = $groupbuy_info['upper_limit'];
        $goods_info['promotions_id'] = $goods_info['groupbuy_id'] = $groupbuy_info['groupbuy_id'];
        $goods_info['ifgroupbuy'] = true;
        //v3-b10
        //$goods_model=Model('order');
        $ordergoods=Model()->table('order_goods')->where(array('buyer_id'=>$_SESSION['member_id'],'goods_type'=>2,'promotions_id'=>$groupbuy_info['groupbuy_id']))->sum('goods_num');
        if(!empty($ordergoods)&&intval($ordergoods)>0)
        {
            $tnum=intval($groupbuy_info['upper_limit'])-intval($ordergoods);//-intval($goods_info['goods_num']);
            if($tnum<=0)
                $goods_info=null;
            //return;
            else{
                if($goods_info['goods_num']>$tnum){
                    $goods_info['goods_num'] = $tnum;
                }
            }
        }
    }

    /**
     * 阶梯价、一口价检测
     * @param $sku
     * @return bool
     */
    private function checkPrice($sku)
    {
        //判断为空
        if (count($sku) == 0) {
            $this->error = '请设置价格';
            return false;
        }
        //判断是否同一种定价方式
        foreach ($sku as $k => $v) {
            if (!Validate::is($v['goods_stock'], 'number')) {
                $this->error = '库存必须为数字！';
                return false;
            }
            if (!Validate::is($v['market_price'], 'float')) {
                $this->error = '市场价格式不正确！';
                return false;
            }
            if (!Validate::is($v['goods_price'], 'require')) {
                $this->error = '销售价不能为空！';
                return false;
            }
            if (!Validate::is($v['goods_freight'], 'float')) {
                $this->error = '运费格式不正确！';
                return false;
            }
            $ladder[] = substr_count($v['goods_price'], ':');
        }
        if (count(array_unique($ladder)) == 1) { //格式一致
            return true;
        } else {
            $this->error = '同一商品一口价、阶梯价只能选择一种';
            return false;
        }
    }

    /**
     * 添加商品
     * @param $data
     * @return bool
     */
    public function addData($data)
    {
        if ($this->checkPrice($data['sku']) == false) {
            return false;
        }
        //添加主表数据
        $data['attr_names'] = '';
        if ($data['attr_id'] > 0) { //获取规格对应值
            foreach ($data['attr'] as $v) {
                $attrName[] = $v['item_name'];
            }
            $data['attr_names'] = implode(',', $attrName);
        }
        //预售商品
        $data['presell_deliverdate'] = 0;
        if ($data['is_presell'] == 1) {
            if (empty($data['presell_deliverdate'])) {
                $this->error = '预售发货日期不能为空！';
                return false;
            }
            $data['presell_deliverdate'] = strtotime($data['presell_deliverdate']);
        }
        $this->isUpdate(false)->allowField(true)->save($data);
        //添加附表数据
        $goodsData['goods_id']    = $this->getData('goods_id');
        $goodsData['content']     = $data['content'];
        $goodsData['base_extend'] = $data['base_extend'];
        $shopGoodsDataModel       = new ShopGoodsDataModel();
        $shopGoodsDataModel->addData($goodsData);
        //添加sku数据
        $goodsSkuModel = new ShopGoodsSkuModel();
        foreach ($data['sku'] as $k => $v) {
            $data['sku'][$k]['goods_id'] = $this->getData('goods_id');
        }
        $goodsSkuModel->saveAll($data['sku']);
        //添加扩展属性
        if (!empty($data['extend'])) {
            $goodsExtendModel = new ShopGoodsExtendModel();
            $extend           = $data['extend'];
            $extendList       = [];
            foreach ($extend as $k => $v) {
                if (!empty($v['item_select'])) {
                    $v['site_id']  = $data['site_id'];
                    $v['goods_id'] = $this->getData('goods_id');
                    $extendList[]  = $v;
                }
            }
            if (!empty($extendList)) {
                $goodsExtendModel->saveAll($extendList);
            }
        }
        return true;
    }

    /**
     * 编辑商品
     */
    public function editData($data)
    {
        if ($this->checkPrice($data['sku']) == false) {
            return false;
        }
        $goodsInfo = $this->get($data['goods_id']);
        //添加主表数据
        $data['attr_names'] = '';
        if ($goodsInfo['attr_id'] > 0) { //获取规格对应值
            foreach ($data['attr'] as $v) {
                $attrName[] = $v['item_name'];
            }
            $data['attr_names'] = implode(',', $attrName);
        }
        //预售商品
        $data['presell_deliverdate'] = 0;
        if ($data['is_presell'] == 1) {
            if (empty($data['presell_deliverdate'])) {
                $this->error = '预售发货日期不能为空！';
                return false;
            }
            $data['presell_deliverdate'] = strtotime($data['presell_deliverdate']);
        }
        $this->isUpdate(true)->allowField(true)->save($data);
        //修改附表数据
        $goodsData['goods_id']    = $data['goods_id'];
        $goodsData['content']     = $data['content'];
        $goodsData['base_extend'] = $data['base_extend'];
        $shopGoodsDataModel       = new ShopGoodsDataModel();
        $shopGoodsDataModel->save($goodsData, ['goods_id' => $data['goods_id']]);
        //修改sku数据 一定不可能混搭sku，只有修改和新增两种套路
        $goodsSkuModel = new ShopGoodsSkuModel();
        $isUpdate      = false; //新增
        foreach ($data['sku'] as $k => $v) {
            if (isset($v['sku_id'])) {
                $isUpdate = true; //更新
                break;
            }
        }
        if ($isUpdate == false) { //新增需先删除旧sku数据
            $goodsSkuModel->where('goods_id', $data['goods_id'])->delete();
            foreach ($data['sku'] as $k => $v) {
                $data['sku'][$k]['goods_id'] = $data['goods_id'];
            }
        }
        $goodsSkuModel->saveAll($data['sku']);
        //添加扩展属性
        if (!empty($data['extend'])) {
            $goodsExtendModel = new ShopGoodsExtendModel();
            $extend           = $data['extend'];
            $extendList       = [];
            foreach ($extend as $k => $v) {
                if (!empty($v['item_select'])) {
                    $v['site_id']  = $data['site_id'];
                    $v['goods_id'] = $this->getData('goods_id');
                    $extendList[]  = $v;
                }
            }
            if (!empty($extendList)) {
                $goodsExtendModel->saveAll($extendList);
            }
        }
        $goodsExtendModel = new ShopGoodsExtendModel();
        if (!empty($data['extend'])) {
            $extend     = $data['extend'];
            $extendList = [];
            foreach ($extend as $k => $v) {
                if (!empty($v['item_select'])) {
                    if (empty($v['id'])) {
                        unset($v['id']);
                    }
                    $v['site_id']  = $data['site_id'];
                    $v['goods_id'] = $this->getData('goods_id');
                    $extendList[]  = $v;
                }
                //选项为空标记为删除
                if ($v['id'] > 0 && empty($v['item_select'])) {
                    $delExendIds[] = $v['id'];
                }
            }
            if (!empty($delExendIds)) {
                $goodsExtendModel->where('id', 'in', $delExendIds)->delete();
            }
            if (!empty($extendList)) {
                $goodsExtendModel->saveAll($extendList);
            } else {
                $goodsExtendModel->where('goods_id', $this->getData('goods_id'))->delete();
            }
        } else { //删除属性
            $goodsExtendModel->where('goods_id', $this->getData('goods_id'))->delete();
        }
        return true;
    }

    /**
     * 删除商品
     * @param $goodsId
     */
    public function delData($goodsId)
    {
        $map['goods_id'] = $goodsId;
        Db::table('shop_goods')->where($map)->delete();
        Db::table('shop_goods_data')->where($map)->delete();
        Db::table('shop_goods_sku')->where($map)->delete();
        Db::table('shop_goods_extend')->where($map)->delete();
        return true;
    }

    /**
     * 检测库存
     * @param integer $skuId skuid
     * @param integer $num 购买数量
     * @return integer 库存-数量后的值
     */
    public function checkStock($skuId, $num)
    {
        $skuInfo    = ShopGoodsSkuModel::get($skuId);
        $goodsStock = $skuInfo->getData('goods_stock');
        return $goodsStock - $num;
    }

    /**
     * 刷新库存 键为skuID 值为购买数
     * $stocks=['1'=>'6','3'=>10,'10'=>100]
     * @param $skuIds
     * @param $nums
     */
    public function refrashStock($stocks)
    {
        $goodsSkuModel = new ShopGoodsSkuModel();
        $info          = $goodsSkuModel->where('sku_id', 'in', array_keys($stocks))->column('goods_stock,goods_name,sku_name', 'sku_id');
        foreach ($stocks as $k => $v) {
            if ($v > $info[$k]['goods_stock']) {
                $this->error = '[' . $info[$k]['goods_name'] . ' ' . $info[$k]['sku_name'] . ']库存不足';
                return false;
            }
        }
        return true;
    }

    /**
     * 计算商品价格
     * @param $goodsPrice
     * @param $num
     * @return bool
     */
    public function calcPrice($goodsPrice, $num)
    {
        $price = format_goods_price($goodsPrice);
        if ($price['is_ladder'] == 1) {
            $goodsLadderNum = array_keys($price['ladder_price']);
            $index          = count($goodsLadderNum) - 1; //最终索引
            if ($num >= $goodsLadderNum[$index]) { //最后一条
                $resultPrice = $price['ladder_price'][$goodsLadderNum[$index]];
            }
            if ($num >= $goodsLadderNum[0] && $num < $goodsLadderNum[$index]) {
                foreach ($goodsLadderNum as $k => $v) {
                    if ($k == $index) {
                        continue;
                    }
                    if ($num >= $v && $num < $goodsLadderNum[$k + 1]) {
                        $resultPrice = $price['ladder_price'][$v];
                    }
                }
            }
            if ($num < $goodsLadderNum[0]) { //第一条
                $this->error = '未达到阶梯价订购最低标准';
                return false;
            }
        } else {
            $resultPrice = $price['simple_price'];
        }
        return $resultPrice;
    }

}
